<template>
  <div class="d-flex flex-col gap-col-8">
    <div class="d-flex flex-col gap-col-4">
      <Card
        v-for="(card, index) in creditCardList"
        :key="`credit-card-${index}`"
        :card="card"
        :selected="card.id === modelValue.id"
        :disabled="card.is_ban"
        dark
        clickable
        check-icon
        @click="onCardClick"
      ></Card>
      <div v-if="cardError" class="font-size-10 font-weight-400 line-height-120 text-primary-x">
        {{ cardError }}
      </div>
    </div>
    <div v-show="false" class="option manage-card" @click="toCardManagement">
      <div class="font-size-14 font-weight-400 line-height-125 text-input">{{ $t('payment.label.manageCard') }}</div>
      <div>
        <Icon name="arrowRight"></Icon>
      </div>
    </div>
    <button class="option manage-card" @click="toAddCard">
      <div class="font-size-14 font-weight-400 line-height-125 text-input">{{ $t('payment.label.addCard') }}</div>
      <div>
        <Icon name="arrowRight"></Icon>
      </div>
    </button>
  </div>
</template>
<script setup>
import { debounce } from 'lodash-es'
import { computed } from 'vue'
import { useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import { useCreditCardStore } from '@/store/credit-card'
import { usePopupDialogStore } from '@/store/popup-dialog'
import { $t } from '@/i18n'
import Card from '@/components/payment/Card.vue'

const props = defineProps({
  modelValue: { type: Object, required: true },
})

const emits = defineEmits(['update:card', 'add:card', 'update:modelValue'])
const modelValue = computed({
  get: () => props.modelValue,
  set: (value) => emits('update:modelValue', value),
})
const cardError = computed(() => (modelValue.value.is_ban ? $t('info.cardError.ban') : ''))
const onCardClick = (card) => (modelValue.value = card)

const creditCardStore = useCreditCardStore()
const { creditCardList } = storeToRefs(creditCardStore)

const router = useRouter()
const { close } = usePopupDialogStore()

const toCardManagement = () => {
  router.replace({ name: 'mine', params: { to: 'purchases' } })
  close()
}

const toAddCard = debounce(() => emits('add:card'), 300)
</script>
<style scoped lang="scss">
.option {
  width: 100%;
  padding: 0.625rem 1rem;
  border-radius: 10px;
  background-color: rgb(var(--v-theme-background));

  cursor: pointer;
}

.manage-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.active {
  box-shadow: 0 0 0 2px rgb(var(--v-theme-primary));
}
</style>
